//
//  CircleDetailViewController.m
//  GolfFriend
//
//  Created by vescky on 13-12-12.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "CircleDetailViewController.h"
#import "CircleCommentCell.h"
#import "MJRefresh.h"
#import "AppsEngine.h"
#import "DXAlertView.h"
#import "SVProgressHUD.h"
#import "UserSession.h"
#import "LitePhotoCollectionView.h"
#import "UIImageView+MJWebCache.h"
#import "DateUtility.h"
#import "CommonUtility.h"
#import "ZanDao.h"
#import <QuartzCore/QuartzCore.h>
#import "ReportSpamViewController.h"

@interface CircleDetailViewController ()<UITextViewDelegate,MJRefreshBaseViewDelegate,UIActionSheetDelegate> {
    NSMutableArray *commentList;
    CircleCommentCell *sampleCell;
    UIView *accessoryView;
    int currentPage;
    CGRect rectInput;
    
    //下拉刷新，上拉加载更多
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    //内容区域
    LitePhotoCollectionView *photosView;
    UILabel *labelContent;
    
    UIButton *btnHideKeyboard;
}

@end

@implementation CircleDetailViewController

@synthesize contentVO,isSupported;

#pragma mark - life-cycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController.navigationBar setHidden:NO];
    [self setTitle:@"正文"];
    [super customBackButton];
    
    [self initView];
    [self initData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
//获取Cell的高度
- (float)getCellHeightWithContent:(NSDictionary*)_dict {
    if (!sampleCell) {
        sampleCell = [[[NSBundle mainBundle] loadNibNamed:@"CircleCommentCell" owner:self options:nil] objectAtIndex:0];
    }
    return [sampleCell getContentHeight:_dict];
}

- (void)initView {
    //初始化刷新view
    _header = [MJRefreshHeaderView header];
    _header.scrollView = cdScrollView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = cdScrollView;
    _footer.delegate = self;
    
    accessoryView = [[UIView alloc] init];
    [accessoryView setFrame:CGRectMake(0, 0, 320, 30)];
    [accessoryView setBackgroundColor:[UIColor greenColor]];
    
    imgvAvatar.layer.cornerRadius = imgvAvatar.frame.size.width / 2.0;
    
//    //监听键盘高度的变换
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//    
//    // 键盘高度变化通知，ios5.0新增的
//#ifdef __IPHONE_5_0
//    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if (version >= 5.0) {
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    }
//#endif
    
    //定制自己的风格的  UIBarButtonItem
    UIButton* jumpButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];//
    [jumpButton setTitle:@"举报" forState:UIControlStateNormal];
    [jumpButton addTarget:self action:@selector(goReport) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:jumpButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
}

- (void)goReport {
    ReportSpamViewController *rsp = [[ReportSpamViewController alloc] init];
    rsp.recordId = contentVO.articleId;
    rsp.reportType = @"circle";
    [self.navigationController pushViewController:rsp animated:YES];
}

- (void)initData {
    currentPage = 1;
    
    if (!contentVO) {
        return;
    }
    
    if (contentVO.userId && contentVO.userId.length > 0) {
        [imgvAvatar setImageURLStr:contentVO.avatar placeholder:Default_Avatar];
    }
    
    if (contentVO.userName && contentVO.userName.length > 0) {
        [labelUserName setText:contentVO.userName];
    }
    else {
        [labelUserName setText:@"匿名"];
    }
    
    if (contentVO.cityName && contentVO.cityName.length > 0) {
        [labelCityName setText:contentVO.cityName];
    }
    else {
        [imgvLocation removeFromSuperview];
        [labelCityName removeFromSuperview];
    }
    
    if (contentVO.zan && contentVO.zan.length > 0) {
        [labelZan setText:contentVO.zan];
    }
    
    if (contentVO.comments && contentVO.comments.length > 0) {
        [labelComment setText:contentVO.comments];
    }
    
    if (contentVO.time && contentVO.time.length > 0) {
        [labelDateTime setText:getStringFromDate(@"MM月dd日",getDateFromString(@"yyyy-MM-dd HH:mm:ss",contentVO.time))];
    }
    
    commentList = [[NSMutableArray alloc] init];
    
    
    //-----  set content label
    float marginForContent = 5.0;
    float fontSizeForContent = 15.0;
    float imageHeight = 200.0;
    
    NSString *contentString = contentVO.content;
    CGSize cSize = [contentString sizeWithFont:[UIFont systemFontOfSize:fontSizeForContent] constrainedToSize:CGSizeMake(viewContent.frame.size.width - 2 * marginForContent,1000) lineBreakMode:0];
    labelContent = [[UILabel alloc] initWithFrame:CGRectMake( marginForContent, marginForContent, viewContent.frame.size.width - 2 * marginForContent, cSize.height )];
    [labelContent setLineBreakMode:0];
    [labelContent setNumberOfLines:0];
    [labelContent setText:contentString];
    [labelContent setFont:[UIFont systemFontOfSize:fontSizeForContent]];
    [labelContent setBackgroundColor:[UIColor clearColor]];
    [viewContent addSubview:labelContent];
    
    CGRect cRect = viewContent.frame;
    
    //-----  set photos collection
    NSArray *imgArr = [contentVO.sourceLinks objectForKey:@"image"];
    if (imgArr && [imgArr count] > 0) {
        photosView = [[LitePhotoCollectionView alloc] init];
        [photosView setPhotoCollection:[[NSMutableArray alloc] initWithArray:imgArr]];
        [photosView setMargin: 5.0];
        [photosView setViewWidth:viewContent.frame.size.width];//与content同宽度
        [photosView setColCount:1];
//        [photosView setScaleHDW:(float)imageHeight/320.0];
        [photosView.view setFrame:CGRectMake(0,
                                             labelContent.frame.origin.y + labelContent.frame.size.height + 2 * marginForContent,
                                             viewContent.frame.size.width - 2 * marginForContent,
                                             [photosView getViewHeight])];
        [viewContent addSubview:photosView.view];
        
        cRect.size.height = photosView.view.frame.origin.y + photosView.view.frame.size.height + 40 - [imgArr count] * 10;
    }
    else {
        cRect.size.height = labelContent.frame.origin.y + labelContent.frame.size.height + 40 + 2 * marginForContent;
    }
    
//    if (cRect.size.height < 80) {
//        cRect.size.height = 80;
//    }
    [viewContent setFrame:cRect];
    
/*    CGRect buttomRect = viewButtom.frame;
    buttomRect.origin.y = cRect.origin.y + cRect.size.height + 8 * marginForContent;
    [viewButtom setFrame:buttomRect];*/
    
    CGRect clRect = tbCommentList.frame;
    clRect.origin.y = cRect.origin.y + cRect.size.height;
    [tbCommentList setFrame:clRect];
    
    [cdScrollView setContentSize:CGSizeMake(cdScrollView.frame.size.width, clRect.origin.y + clRect.size.height - 50)];
    
    [self getCommentData];
    
//    NSDictionary *dictZ = [[NSDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userId",@"circle",@"type",contentVO.articleId,@"recordId", nil];
//    isSupported = [[ZanDao shareZanDao] checkIfZaned:dictZ];
//    [btnZan setSelected:isSupported];
    
    switch ([contentVO.isSupported intValue]) {
        case 0:
            btnZan.selected = NO;
            break;
        case 1:
            btnZan.selected = YES;
            break;
        case 2:
            btnZan.enabled = NO;
            break;
            
        default:
            break;
    }
}

- (void)refreshTableView {
    if (!commentList || [commentList count] < 1) {
        if (currentPage <= 1) {
            [self showNoCommentView];//第一次请求，没有数据就显示无数据view
        }
    }
    else {
        [tbCommentList setHidden:NO];
        [tbCommentList reloadData];
        currentPage++;//评论页码加一
        float tbHeight = [self getTableViewHeightWithDataArray:commentList];
        CGRect tbRect = tbCommentList.frame;
        tbRect.size.height = tbHeight;
        [tbCommentList setFrame:tbRect];
        [cdScrollView setContentSize:CGSizeMake(cdScrollView.contentSize.width, tbRect.origin.y + tbRect.size.height + 20)];
    }
}

- (float)getTableViewHeightWithDataArray:(NSArray*)_arr {
    if (!_arr || [_arr count] <= 0) {
        _arr = commentList;//默认参数
    }
    float tbHeight = 0;
    for (int i = 0; i < [_arr count]; i++) {
        tbHeight = tbHeight + [self getCellHeightWithContent:[_arr objectAtIndex:i]];
    }
    //无数据，返回无数据的高度
    if (tbHeight <= 0) {
        return 0;
    }
    return tbHeight;
}

- (void)getCommentData {
    if (currentPage <= 1) {
        [self enableAnimating:YES];
    }
    
    //网上请求数据
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",currentPage],@"page",
                                 contentVO.articleId,@"articleId", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetArticleComments" param:dict onCompletion:^(id jsonResponse) {
        if (currentPage <= 1) {
            [self enableAnimating:NO];
            [viewNoComment removeFromSuperview];
        }
        
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"刷新成功");
            NSMutableArray *commentArr = [jsonResponse objectForKey:@"content"];
            commentList = [self combileArray:commentList withArray:commentArr];
            [self refreshTableView];
        }
        
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        if (currentPage <= 1) {
            [self enableAnimating:NO];
        }
//        DXAlertView *dAlert = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"暂无网络连接!无法获取评论!" leftButtonTitle:nil rightButtonTitle:@"确定"];
//        [dAlert show];
        [self showNoCommentView];
    } method:@"GET"];
}

- (NSMutableArray*)combileArray:(NSMutableArray*)arr1 withArray:(NSMutableArray*)arr2 {
    if (!arr1 || ![arr1 respondsToSelector:@selector(count)]) {
        return arr2;
    }
    if (!arr2 || ![arr2 respondsToSelector:@selector(count)]) {
        return arr1;
    }
    
    for (int i = 0; i < [arr2 count]; i++) {
        [arr1 addObject:[arr2 objectAtIndex:i]];
    }
    return arr1;
}

- (bool)checkForm {
    if ([tvComment.text length] < 1) {
        [SVProgressHUD showErrorWithStatus:@"评论内容不能为空!"];
        return NO;
    }
    return YES;
}

- (void)showNoCommentView {
    [tbCommentList setHidden:YES];
    CGRect nRect = viewNoComment.frame;
    nRect.origin.y = viewContent.frame.origin.y + viewContent.frame.size.height;
    [viewNoComment setFrame:nRect];
    [cdScrollView addSubview:viewNoComment];
}

- (void)enableAnimating:(bool)_enable {
    if (_enable) {
        [viewLoadingComment setFrame:CGRectMake(0, viewContent.frame.origin.y + viewContent.frame.size.height + 20, cdScrollView.frame.size.width, 100)];
        [cdScrollView addSubview:viewLoadingComment];
        [clActivityIndicator startAnimating];
    }
    else {
        [viewLoadingComment removeFromSuperview];
        [clActivityIndicator stopAnimating];
    }
}

- (void)hideKeyboard {
    [tvComment resignFirstResponder];
    [btnHideKeyboard removeFromSuperview];
    btnHideKeyboard = nil;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [commentList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CircleCommentCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CircleCommentCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setDataInfo:)]){
        [cell performSelector:@selector(setDataInfo:) withObject:[commentList objectAtIndex:indexPath.row]];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self getCellHeightWithContent:[commentList objectAtIndex:indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    NSLog(@"keyboard shown");
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    viewMask.hidden = NO;
    commentPannel.hidden = NO;
    commentPannel.frame = CGRectMake(0,keyboardRect.origin.y - 170.f - 64.f, 320.f, 255.f);
    
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSLog(@"keyboard hidden");
    viewMask.hidden = YES;
    commentPannel.hidden = YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    textView.inputAccessoryView = commentPannel;
    commentPannel.hidden = NO;
    return YES;
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) {
        // 下拉刷新
        if (commentList) {
//            [commentList removeAllObjects];
        }
    }
    [self getCommentData];
}


#pragma mark - Button Action
- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 200) {
        //点赞
        if (isSupported) {
            [SVProgressHUD showErrorWithStatus:@"您已赞过!"];
            return;
        }
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:contentVO.articleId,@"articleId",@"circle",@"type", nil];
        [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishZan" param:params onCompletion:^(id jsonResponse) {
            NSLog(@"zan success");
        } onError:^(NSError *error) {
            
        } method:@"GET"];
        
        //缓存到本地
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userId",
                              @"circle",@"type",contentVO.articleId,@"recordId",nil];
        [[ZanDao shareZanDao] saveZanInfo:dict];
        isSupported = YES;
        labelZan.text = [NSString stringWithFormat:@"%d",[labelZan.text intValue]+1];
        [btnZan setSelected:YES];
        
        contentVO.zan = labelZan.text;
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Article_Comment_Published object:contentVO];
    }
    else if (btn.tag == 201) {
        //发送评论
        if ([self checkForm]) {
            NSLog(@"发送评论，刷新评论列表，隐藏键盘");
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:contentVO.articleId,@"articleId",[[UserSession shareUserSession] getUserId],@"fromID",tvComment.text,@"content", nil];
            [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishCircleComment" param:params onCompletion:^(id jsonResponse) {
                NSLog(@"comment success");
                [SVProgressHUD showSuccessWithStatus:@"评论成功!"];
            } onError:^(NSError *error) {
                
            } method:@"GET"];
            contentVO.comments = [NSString stringWithFormat:@"%d",[contentVO.comments intValue] + 1];
            [labelComment setText:contentVO.comments];
            
            //local使用
            NSString *myAvatar = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"avatar"];
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"刚刚",@"time",
                                  tvComment.text,@"content",
                                  [[UserSession shareUserSession] getUserName],@"nickName",
                                  myAvatar ? myAvatar : @"",@"avatar",nil];
            [commentList addObject:dict];
            [self refreshTableView];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Article_Comment_Published object:contentVO];
            [tvComment resignFirstResponder];
            tvComment.text = @"";
            
            [viewNoComment setHidden:YES];
        }
    }
    else if (btn.tag == 202) {
        //弹出评论
        [tvComment becomeFirstResponder];
    }
    else if (btn.tag == 203) {
        //赞 -- 无用
    }
    else if (btn.tag == 204) {
        //收起评论
        [tvComment resignFirstResponder];
    }
}

@end
